﻿using AutoMapper;
using MediatR;
using Traceability.Commont.Domains;
using Traceability.Commont.DTOs.CommontFiles;
using Traceability.Commont.DTOs.UsersFile;
using Traceability.Commont.Infrastructures.Interfaces;

namespace Traceability.Api.Applications.Roless
{
    public class RolesListHander : IRequestHandler<RolesListCommand, Resqults<RolesListDTO>>
    {
        private readonly IBateRepository<RolesPermissiont> rolesPer;
        private readonly IBateRepository<Permissions> per;
        private readonly IBateRepository<Roles> roles;
        private readonly IMapper mapper;

        public RolesListHander(IBateRepository<RolesPermissiont> rolesPer, IBateRepository<Permissions> per, IBateRepository<Roles> roles, IMapper mapper)
        {
            this.rolesPer = rolesPer;
            this.per = per;
            this.roles = roles;
            this.mapper = mapper;
        }

        public async Task<Resqults<RolesListDTO>> Handle(RolesListCommand request, CancellationToken cancellationToken)
        {
            var resq= new Resqults<RolesListDTO>();
            var list = from a in roles.GetAll()
                       join b in rolesPer.GetAll() on a.RolesId equals b.RolesId
                       join c in per.GetAll() on b.PermissionsId equals c.PermissionsId
                       group new {a,c} by new {a.RolesName,a.RolesId} into e
                       select new RolesListDTO
                       {
                           RolesId = e.Key.RolesId,

                           RolesName = e.Key.RolesName,
                           PerList = string.Join(",",e.Select(x=>x.c.PermissionsName))
                       };
            if (!string.IsNullOrEmpty(request.RolesName))
            {
                list = list.Where(x => x.RolesName.Contains(request.RolesName));
            }
            resq.Date=list.ToList();
            return resq;
        }

        //public  IQueryable getString(int id)
        //{
        //    try
        //    {
        //        var list = from a in rolesPer.GetAll()
        //                   join b in per.GetAll() on a.PermissionsId equals b.PermissionsId
        //                   where a.RolesId == id
        //                   select b;
        //        var res = list.Select(x => x.PermissionsName);
        //        return res;
        //    }
        //    catch (Exception)
        //    {

        //        throw;
        //    }
        //}
    }
}
